<template>
  <div class="v-editor-selects">
    <div class="g-flex-1">
      <MDropdown
        v-for="(valueModel, index) of valueModels"
        :key="index"
        :disabled="row.readonly || isModelDisabled"
        lazy
        :loadListCallback="loadOptions"
      >
        <div
          class="g-jc-sb g-pd-l-8 g-pointer"
          :class="{ _selected: valueModel.selected }"
          @click="handleClickModel(valueModel)"
        >
          <div class="g-flex-1">
            {{ locale.getTByContent(valueModel.name, valueModel.name, { en: "enLabel", zhCn: "label" }) }}
          </div>
          <div
            v-if="valueModel.selected && !row.readonly && !isModelDisabled"
            class="g-flex-0 g-pd-lr-4"
          >
            <img
              src="statics/icons/app/iconlist2.png"
              @click="handleClick"
            />
          </div>
        </div>
        <template #dropdown>
          <MDropdownMenuItem
            v-for="item in options"
            :key="item.value"
            class="g-one-line"
            @click="handleClickItem(valueModel, item, index)"
          >
            {{ locale.getTByContent(item, item.label, { en: "enLabel", zhCn: "label" }) }}
          </MDropdownMenuItem>
        </template>
      </MDropdown>
    </div>
    <div
      v-if="selected && !row.readonly && !isModelDisabled && mode !== 'horizontal'"
      style="border-left: 1px solid #ddd; line-height: 14px"
      class="g-pd-4 g-flex-0"
    >
      <div>
        <img
          src="statics/icons/app/iconadd.png"
          class="g-pointer"
          @click="handleAdd"
        />
      </div>
      <div class="g-m-t-4">
        <img
          src="statics/icons/app/iconreduce.png"
          class="g-pointer"
          :class="{ _disable: disabledRemove }"
          @click="handleRemove"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, Ref, inject } from "vue";
import { ModelValue, PropertyDropdownOption, PropertyRow } from "../../types";
import { propertyUtil } from "../../PropertyUtil";
import { BusEvent, PropertyKey } from "@/constants/Enums";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";
import { locale } from "@/util/locale";
import { useLoadItemsOptions } from "./useLoadOptions";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 普通下拉选择，处理多重枚举型属性的拉下选择 比如属性多重性测试.md3-模块构造型-高度
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  mode?: string; // 新增横向horizontal模式, 以便在一行内显示内容
}>();

// const options = ref<PropertyDropdownOption[]>([]);

const clientY = ref(0);

const { options, loadOptions } = useLoadItemsOptions(props.row);

const handleClick = (target: MouseEvent) => {
  clientY.value = target.clientY;
};
const selectedModelId = ref("");

const valueModels = computed(() => {
  console.log(props, "000000000");
  return (props.row.value || []) as (ModelValue & { selected: boolean })[];
});

// const selectedOption = computed(() => {
//   console.log(props.row);
//   if (props.row.items) {
//     if ((props.row.value as ModelValue)?.id) {
//       return props.row.items.find(it => (it.value) === (props.row.value as ModelValue)?.id);
//     } else {
//       return props.row.items.find(it => (it.value) === props.row.value);
//     }

//   } else {
//     return null;
//   }
// });

function handleClickItem(valueModel: ModelValue, item: PropertyDropdownOption, index: number) {
  if ([PropertyKey.ItemFlow_name, PropertyKey.ItemFlow_direction].includes(props.row.key as any)) {
    app.$bus.emit(BusEvent.EDITOR_CHANGE, props.row, item.value);
    props.row.value = item.value;
  } else {
    const newValue = valueModels.value.map(it => it.id);
    newValue[index] = item.value;
    // 更新属性是共性行为
    propertyUtil.updatePropertyAndFresh(props.row, newValue);
  }
}

function handleClickModel(item: ModelValue & { selected: boolean }) {
  valueModels.value.forEach(it => {
    it.selected = false;
  });
  item.selected = true;
  selectedModelId.value = item.id;
}
const disabledRemove = computed(() => {
  return valueModels.value.length == 0 || (props.row.nullable === false && valueModels.value.length == 1);
});
async function handleRemove() {
  if (disabledRemove.value) return;
  if (!selectedModelId.value) {
    app.$notify({
      title: "提示",
      type: "error",
      message: "请选中元素再操作移除"
    });
    return;
  }
  const index = valueModels.value.filter(it => it.id === selectedModelId.value).findIndex(it => it.selected);
  await propertyUtil.removePropertyAndRefresh(props.row, selectedModelId.value, true, index);
}

async function handleAdd() {
  await loadOptions();
  if (!options.value[0]) return;
  await propertyUtil.appendPropertyAndFresh(props.row, [options.value[0].value]);
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/theme.scss";
.v-editor-selects {
  display: flex;
  ._selected {
    color: $theme-color;
  }
}
</style>
